package network.tcp;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

//客户端
public class TcpClient {


    public static void main(String[] args) {
        Socket socket = null;
        OutputStream stream = null;

        try {
            //1.客户端获取服务器地址
            InetAddress serverIP = InetAddress.getByName("localhost");
            int port = 10011;

            //2.创建一个Socket连接
            socket = new Socket(serverIP, port);

            //3.发消息 IO流
            stream = socket.getOutputStream();
            stream.write("你好，我是CphRed。".getBytes(StandardCharsets.UTF_8));

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if (stream!=null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
